package com.yu.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yu.crm.domain.dto.WxCpDepartReq;
import com.yu.crm.domain.pojo.CrmDepartment;
import com.yu.crm.domain.pojo.CrmDepartmentPosition;
import com.yu.crm.domain.pojo.CrmDepartmentPositionLevel;
import com.yu.crm.domain.pojo.CrmDepartmentPositionType;
import com.yu.crm.feign.remote.CrmUserFeignRemote;
import com.yu.crm.mapper.CrmDepartmentMapper;
import com.yu.crm.service.CrmDepartmentPositionLevelService;
import com.yu.crm.service.CrmDepartmentPositionService;
import com.yu.crm.service.CrmDepartmentPositionTypeService;
import com.yu.crm.service.CrmDepartmentService;
import com.yxzz.common.BaseServiceImpl;
import com.yxzz.common.exception.GeneralException;
import com.yxzz.common.helper.DataHelpers;
import com.yxzz.common.helper.DateHelpers;
import com.yxzz.common.helper.ExceptionHelpers;
import com.yxzz.common.helper.valid.ValidatorHelpers;

import me.chanjar.weixin.cp.bean.WxCpDepart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 部门信息表 服务实现类
 * </p>
 *
 * @author donnie-bin
 * @since 2019-06-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CrmDepartmentServiceImpl extends BaseServiceImpl<CrmDepartmentMapper, CrmDepartment> implements CrmDepartmentService {
    @Autowired
    CrmDepartmentPositionService crmDepartmentPositionService;
    @Autowired
    CrmDepartmentPositionLevelService crmDepartmentPositionLevelService;
    @Autowired
    CrmDepartmentPositionTypeService crmDepartmentPositionTypeService;
    @Autowired
    private CrmUserFeignRemote crmUserFeignRemote;
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public boolean saveOrUpdate(CrmDepartment entity) {
        if(DataHelpers.isEmpty(entity.getId())){
            WxCpDepartReq depart=new WxCpDepartReq();
            if((entity.getPid())!=null){
                depart.setParentId(entity.getPid());
            }else{
                throw new GeneralException("父部门id不能为空");
            }
            if(DataHelpers.isNotEmpty(entity.getDepartmentName())){
                depart.setName(entity.getDepartmentName());
            }else{
                throw new GeneralException("部门名称不能为空");
            }
            depart.setAgentId(1000012);
            //新增部门
            HashMap<String,Object> maps = crmUserFeignRemote.createDept(depart    );
            if(DataHelpers.isNotEmpty(maps)){
                HashMap<String,Object> map = (HashMap<String,Object>)maps.get("data");
                if(DataHelpers.isNotEmpty(map.get("id"))){
                    LambdaQueryWrapper<CrmDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(CrmDepartment::getPid, entity.getPid());
                    lambdaQueryWrapper.eq(CrmDepartment::getDepartmentName, entity.getDepartmentName());
                    //QueryWrapper<CrmDepartmentFeignFallbackFactory> queryWrapper = new QueryWrapper<>();
                    //queryWrapper.eq("pid", entity.getPid()).eq("department_name", entity.getDepartmentName());
                    int oldCount = super.count(lambdaQueryWrapper);
                    ValidatorHelpers.validateDataExist("子部门名称不能重复", oldCount);
                    entity.setGmtCreate(DateHelpers.now());
                    entity.setGmtModified(DateHelpers.now());
                    entity.setId(Long.parseLong(map.get("id").toString()));
                    entity.setSort(Long.parseLong(map.get("order").toString()));

                    ExceptionHelpers.checkData(super.save(entity), "新增失败");

                    return true;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }else{
            entity.setGmtModified(DateHelpers.now());
            ExceptionHelpers.checkData(super.updateById(entity), "更新失败");

            WxCpDepartReq depart=new WxCpDepartReq();
            if(DataHelpers.isNotEmpty(entity.getId())){
                depart.setId(entity.getId());
            }else{
                throw new GeneralException("部门编号不能为空");
            }

            if((entity.getPid())!=null){
                depart.setParentId(entity.getPid());
            }
            if(DataHelpers.isNotEmpty(entity.getDepartmentName())){
                depart.setName(entity.getDepartmentName());
            }

            if(DataHelpers.isNotEmpty(entity.getSort())){
                depart.setOrder(entity.getSort());
            }
            depart.setAgentId(1000012);
            //修改部门
            crmUserFeignRemote.updateDept(depart);
            return true;
        }
    }

    @Override
    public boolean removeById(Serializable id) {
        return ExceptionHelpers.checkData(super.removeById(id), "删除失败");
    }

    @Override
    public CrmDepartment getById(Serializable id) {
        return baseMapper.getById(id);
    }

    public IPage<CrmDepartment> list(IPage<CrmDepartment> page, CrmDepartment queryInfo){
        LambdaQueryWrapper<CrmDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //QueryWrapper<CrmDepartmentFeignFallbackFactory> queryWrapper=new QueryWrapper<>();
        if(DataHelpers.isNotEmpty(queryInfo.getPid())){
            //queryWrapper.eq("pid", queryInfo.getPid());
            lambdaQueryWrapper.eq(CrmDepartment::getPid, queryInfo.getPid());
        }
        if(DataHelpers.isNotEmpty(queryInfo.getDepartmentName())){
            //queryWrapper.like("department_name", queryInfo.getDepartmentName());
            lambdaQueryWrapper.like(CrmDepartment::getDepartmentName, queryInfo.getDepartmentName());
        }
        //queryWrapper.orderByDesc("gmt_modified");
        lambdaQueryWrapper.orderByDesc(CrmDepartment::getGmtModified);
        return super.page(page, lambdaQueryWrapper);
    }

    @Override
    public List<CrmDepartment> treeList(Long pid) {
        return baseMapper.selectTreeList(pid);
    }

    /**
     * 通过部门id查询部门职位集合
     * @param page
     * @param id 部门id
     * @param condition 条件
     * @return
     */
    @Override
    public IPage<CrmDepartmentPosition> pageByDepartmentId(Page<CrmDepartmentPosition> page, Long id, String condition) {
        IPage<CrmDepartmentPosition> iPage=new Page<>();
        QueryWrapper<CrmDepartmentPosition> queryWrapper=new QueryWrapper<>();
        List<Long> ids=new ArrayList<>();
        if(DataHelpers.isNotEmpty(id)){
            //查询当前部门所有子项部门集合
            List<CrmDepartment> list = list(id);
            if(DataHelpers.isNotEmpty(list)) {
                ids = list.stream().map(CrmDepartment::getId).collect(Collectors.toList());
            }
            ids.add(id);
        }
        if(DataHelpers.isNotEmpty(ids)){
            queryWrapper.in("department_id",ids);
        }
        queryWrapper.eq("is_deleted",0);
        if(DataHelpers.isNotEmptyString(condition)){
            queryWrapper.and(x->
                    x.like("position_name",condition).or().like("position_desc",condition)
            );
        }
        iPage= crmDepartmentPositionService.page(page, queryWrapper);
        List<CrmDepartmentPosition> records = iPage.getRecords();
        if(DataHelpers.isNotEmpty(records)){
            //部门职位级别
            List<CrmDepartmentPositionLevel> levelList = crmDepartmentPositionLevelService.list();
            //部门职位类别
            List<CrmDepartmentPositionType> typeList = crmDepartmentPositionTypeService.list();
            if(DataHelpers.isNotEmpty(levelList)){
                for(CrmDepartmentPosition position:records){
                    for(CrmDepartmentPositionLevel level:levelList){
                        if(DataHelpers.isNotEmpty(position.getPositionLevelId()) && position.getPositionLevelId().equals(level.getId())){
                            position.setPositionLevelName(level.getPositionLevelName());
                        }
                    }

                    for(CrmDepartmentPositionType type:typeList){
                        if(DataHelpers.isNotEmpty(position.getPositionTypeId()) && position.getPositionTypeId().equals(type.getId())){
                            position.setPositionTypeName(type.getPositionTypeName());
                        }
                    }
                }
            }
        }
        return iPage;
    }

    /**
     * @param id
     */
    @Override
    public void removeById(Long id) {
        CrmDepartment crmDepartment = baseMapper.selectById(id);
        if(DataHelpers.isNotEmpty(crmDepartment)){
            HashMap<String,Long> map=new HashMap<>();
            map.put("agentId",1000012L);

            List<CrmDepartment> list = list(id);
            if(DataHelpers.isNotEmpty(list)){
                List<Long> ids = list.stream().map(CrmDepartment::getId).collect(Collectors.toList());
                ids.add(id);
                for(Long id1:ids){
                    map.put("id",id1);
                    crmUserFeignRemote.deleteDept(map);
                }
                baseMapper.deleteBatchIds(ids);
            }else{
                map.put("id",id);
                crmUserFeignRemote.deleteDept(map);
                baseMapper.deleteById(id);
            }

        }
    }

    /**
     * 通过部门编号向上移动一位排序
     * @param id 部门编号
     */
    @Override
    public void updateSort(Long id) {
        List<CrmDepartment> departmentList=new ArrayList<>();
        CrmDepartment newCrmDepartment= baseMapper.selectById(id);
        if(DataHelpers.isNotEmpty(newCrmDepartment)){
            QueryWrapper<CrmDepartment> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("pid",newCrmDepartment.getPid());
            queryWrapper.eq("is_deleted",0);
            queryWrapper.orderByAsc("sort");
            List<CrmDepartment> list= baseMapper.selectList(queryWrapper);
            if(DataHelpers.isNotEmpty(list)){
                int i=0;
                for(CrmDepartment department:list){
                    if(!department.getId().equals(newCrmDepartment.getId())){
                        i++;
                    }else{
                        break;
                    }
                }

                if(i>=1){
                    CrmDepartment oldCrmDepartment = list.get(i - 1);
                    if(DataHelpers.isNotEmpty(oldCrmDepartment)){
                        //新排序
                        Long sort = oldCrmDepartment.getSort();
                        oldCrmDepartment.setSort(newCrmDepartment.getSort());
                        newCrmDepartment.setSort(sort);

                        departmentList.add(newCrmDepartment);
                        departmentList.add(oldCrmDepartment);
                    }
                }
                if(DataHelpers.isNotEmpty(departmentList)){
                    saveOrUpdateBatch(departmentList);

                    for(CrmDepartment department:departmentList){
                        WxCpDepartReq depart=new WxCpDepartReq();
                        if(DataHelpers.isNotEmpty(department.getId())){
                            depart.setId(department.getId());
                        }else{
                            throw new GeneralException("部门编号不能为空");
                        }

                        if((department.getPid())!=null){
                            depart.setParentId(department.getPid());
                        }
                        if(DataHelpers.isNotEmpty(department.getDepartmentName())){
                            depart.setName(department.getDepartmentName());
                        }

                        if(DataHelpers.isNotEmpty(department.getSort())){
                            depart.setOrder(department.getSort());
                        }
                        depart.setAgentId(1000012);
                        //修改部门
                        crmUserFeignRemote.updateDept(depart);
                    }
                }
            }
        }else{
            throw new GeneralException("此部门编号无效");
        }
    }

    /**
     * 通过部门id查询当前部门及子项部门
     * @param pid
     * @return
     */
    @Override
    public List<CrmDepartment> list(Long pid) {
        List<CrmDepartment> departments = treeList(pid);
        if(DataHelpers.isNotEmpty(departments)){
            Stream<CrmDepartment> stream = flatTree(departments);
            return stream.collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<Long> getPid(long id, List<Long> idList) {
        CrmDepartment crmDepartment = baseMapper.selectById(id);
        if (DataHelpers.isNotEmpty(crmDepartment)) {
            if (crmDepartment.getPid().toString().equals("0")) {
                //顶级部门
                return idList;
            }else {
                idList.add(crmDepartment.getPid());
                this.getPid(crmDepartment.getPid(),idList);
            }
        }
        return idList;
    }


    /**
     * 树形结构转集合对象
     * @param list
     * @return
     */
    private Stream<CrmDepartment> flatTree(List<CrmDepartment> list){
        Stream<CrmDepartment> stream = list.stream();
        for (CrmDepartment department: list) {
            List<CrmDepartment> children = department.getChildren();
            if (children == null || children.size() < 1) continue;

            stream = Stream.concat(stream, flatTree(children));
        }
        return stream;
    }
}
